package com.linkage.seapeak.activity.project;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.ProCrDecReviewInfo;
import com.linkage.jz.bankruptcy.bean.ZQBaseProjectCrDecInfo;
import com.linkage.jz.bankruptcy.bean.ZQBaseTagInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.BitmapUtil;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PopupMenuExamineInfo;
import com.linkage.seapeak.activity.user.ImageShowActivity;
import com.linkage.seapeak.activity.user.NewImageShowActivity;
import com.linkage.seapeak.base.BaseFragment;
import com.linkage.seapeak.fragment.ExamineInfoFragment;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.utils.FileUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 审查意见详情--- 一般债权人 或者  税务机关债券人
 */
public class CreditorReviewDetailActivity extends BaseCreateActivity {

    public static final String INTENT_IS_TAX_MODE         = "isTaxMode";//true：税务机关；false：债券一般债券人
    public static final String INTENT_IS_MANAGE_TYPE      = "IsManageType";//true:管理人 false：债权人
    public static final String INTENT_IS_REPLENISH_REVIEW = "isReplenishOrReviewPage";//true:补充 类型

    public static final String INTENT_ID_PROJECT         = "ProjectId";
    public static final String INTENT_ID_CREDITOR_RIGHTS = "CreditorRightsId";
    public static final String INTENT_ID_REVIEW          = "ReviewId";
    public static final String INTENT_REVIEW_STATUS      = "ReviewStatus";

    public static final String INTENT_SEND_STATUS      = "showBt";

    private BaseFragment mBaseFragment;

    private String mProjectId;
    private String mCreditorRightsId;
    private String mReviewId;

    private boolean isManageType;//true:管理人 false：债权人
    private boolean isReplenishOrReviewPage;//true：补充  类型
    private boolean isTaxMode;//true：一般债券人；false：税务机关债券

    private int sendStatus;//0--暂存，1--提交生成

    private Boolean showBt;//true显示 false不显示
    /**
     * 债权人:
     * 无菜单
     * 管理人:
     * 审查意见已发送 - 菜单只有『生成图片』 （reviewStatus =1
     * 审查意见未发送 - 菜单是『修改审查意见』和『生成图片』 （reviewStatus =3）
     */
    private int mReviewStatus;

    private PopupMenuExamineInfo mRightMenu;

    @Override
    protected void onCreate( Bundle savedInstanceState ) {
        setContentView(R.layout.activity_examine_review_page);
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {

    }

    @Override
    public void initTitle() {

    }

    private boolean noshowMenu = false;


    public  void setShowMenu(Boolean flag)
    {
        noshowMenu = flag;
        if(noshowMenu)
        {
            setOptionAction();
        }else{
            if (isManageType) {
                mRightMenu = new PopupMenuExamineInfo(this, mReviewStatus);
                titlebar_menu.setVisibility(View.VISIBLE);
                titlebar_menu.setOnClickListener(view -> {
                    mRightMenu.showLocation(R.id.titlebar_menu);// 设置弹出菜单弹出的位置
                    // 设置回调监听，获取点击事件
                    mRightMenu.setOnItemClickListener(( item, str ) -> {
                        if (item == PopupMenuExamineInfo.MENUITEM.ITEM1) {//修改审查意见
                            if (mBaseFragment != null && mBaseFragment instanceof ExamineInfoFragment) {
                                final ExamineInfoFragment fragment = (ExamineInfoFragment) mBaseFragment;
                                if (fragment != null) {
                                    //修改审查等于初次填写
//                                        isReplenishOrReviewPage = false;

                                    fragment.jumpEditInfoPage(isReplenishOrReviewPage,true,true,true);
                                }
                            }
                        } else if (item == PopupMenuExamineInfo.MENUITEM.ITEM2) {//生成图片
//                            onGenerateImage();

                            showImage();
                        }
                    });
                });

            } else {
                setOptionAction();
            }
        }
    }
    @Override
    public void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            isManageType = intent.getBooleanExtra(INTENT_IS_MANAGE_TYPE, true);
            isReplenishOrReviewPage = intent.getBooleanExtra(INTENT_IS_REPLENISH_REVIEW, false);
            isTaxMode = intent.getBooleanExtra(INTENT_IS_TAX_MODE, false);
            mProjectId = intent.getStringExtra(INTENT_ID_PROJECT);
            mCreditorRightsId = intent.getStringExtra(INTENT_ID_CREDITOR_RIGHTS);
            mReviewId = intent.getStringExtra(INTENT_ID_REVIEW);
            mReviewStatus = intent.getIntExtra(INTENT_REVIEW_STATUS, 0);

            showBt = intent.getBooleanExtra(INTENT_SEND_STATUS, true);
            if(noshowMenu)
            {
                setOptionAction();
            }else if (mReviewStatus == 1 && !isReplenishOrReviewPage) {//重新审查

                setOptionAction();
            } else {
                //右上角···操作
                if (isManageType) {
                    mRightMenu = new PopupMenuExamineInfo(this, mReviewStatus);
                    titlebar_menu.setVisibility(View.VISIBLE);
                    titlebar_menu.setOnClickListener(view -> {
                        mRightMenu.showLocation(R.id.titlebar_menu);// 设置弹出菜单弹出的位置
                        // 设置回调监听，获取点击事件
                        mRightMenu.setOnItemClickListener(( item, str ) -> {
                            if (item == PopupMenuExamineInfo.MENUITEM.ITEM1) {//修改审查意见
                                if (mBaseFragment != null && mBaseFragment instanceof ExamineInfoFragment) {
                                    final ExamineInfoFragment fragment = (ExamineInfoFragment) mBaseFragment;
                                    if (fragment != null) {
                                        //修改审查等于初次填写
//                                        isReplenishOrReviewPage = false;

                                        fragment.jumpEditInfoPage(isReplenishOrReviewPage,true,true,true);
                                    }
                                }
                            } else if (item == PopupMenuExamineInfo.MENUITEM.ITEM2) {//生成图片
//                                onGenerateImage();
                                showImage();

                            }
                        });
                    });

                } else {
                    setOptionAction();
                }
            }
            onChangePageStatus();
            titlebar_back.setOnClickListener(view -> onBackPressed());
            if (isReplenishOrReviewPage) {
                titlebar_title.setText("补充审查意见");
            } else {
                titlebar_title.setText("审查意见");
            }
        }
    }

    private void setOptionAction() {
        titlebar_menu.setVisibility(View.GONE);
        titlebar_menu_text.setVisibility(View.VISIBLE);
        titlebar_menu_text.setText("生成图片");
        titlebar_menu_text.setOnClickListener(view -> showImage());
    }

    private void showImage()
    {
        if(mReviewId==null || "".equalsIgnoreCase(mReviewId))
        {
            getDetailInfo();
        }else {
            showImageDetail();
        }
    }

    private void onGenerateImage() {
        if (mBaseFragment != null && mBaseFragment instanceof ExamineInfoFragment) {
            final ExamineInfoFragment fragment = (ExamineInfoFragment) mBaseFragment;
            if (fragment != null) {
                //todo  需加获取写入SD卡权限，兼容高版本
                Observable.just("")
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(s -> {
                            Bitmap bitmap = BitmapUtil.compressImage(BitmapUtil.getBitmapByView(fragment.getScrollView()));
                            FileUtils.savePic(CreditorReviewDetailActivity.this, bitmap, Consts.SD_DIR_SCREENSHOT);

                        });
            } else {
                showToast("生成图片异常，请重试");
            }
        }
    }

    @Override
    public void setListener() {

    }

    @Subscribe
    public void onEvent( String type ) {
        if (type.equals("reSubmitInfo")) {
            onBackPressed();
        }
    }

    public void onChangePageStatus() {
        //查看审查意见
        mBaseFragment = ExamineInfoFragment.getInstance(isManageType, isTaxMode, isReplenishOrReviewPage, mProjectId, mReviewId, mCreditorRightsId, mReviewStatus,showBt);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content, mBaseFragment).commitAllowingStateLoss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }



    private List<UploadImage> list = new ArrayList<>();
    private void showImageDetail() {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        if(isManageType) {
            Network
                    .getAPIService()
                    .creatImg_m(mReviewId, mProjectId, userToken)
                    .subscribeOn(rx.schedulers.Schedulers.io())
                    .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
                    .subscribe(new BaseSubscriber<JsonObject>() {
                        @Override
                        public void onNext(JsonObject json) {
                            int code = json.get("code").getAsInt();
                            if (code != 0) {
                                super.onNext(json);
                                return;
                            }
//                        ToastUtil.showShort("提交成功");

                           String strurl = json.getAsJsonObject("data").get("imageTokenUrl").getAsString();
                            String strdownurl = json.getAsJsonObject("data").get("imageTokenUrl_wmark").getAsString();


                            NewImageShowActivity.start(CreditorReviewDetailActivity.this, strurl,strdownurl);
                        }

                        @Override
                        public void onCompleted() {
                            super.onCompleted();
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                        }
                    });
        }else{
            Network
                    .getAPIService()
                    .creatImg(mReviewId, mProjectId, userToken)
                    .subscribeOn(rx.schedulers.Schedulers.io())
                    .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
                    .subscribe(new BaseSubscriber<JsonObject>() {
                        @Override
                        public void onNext(JsonObject json) {
                            int code = json.get("code").getAsInt();
                            if (code != 0) {
                                super.onNext(json);
                                return;
                            }
                            String strurl = json.getAsJsonObject("data").get("imageTokenUrl").getAsString();
                            String strdownurl = json.getAsJsonObject("data").get("imageTokenUrl_wmark").getAsString();


                            NewImageShowActivity.start(CreditorReviewDetailActivity.this, strurl,strdownurl);
//                        ToastUtil.showShort("提交成功");
                        }

                        @Override
                        public void onCompleted() {
                            super.onCompleted();
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                        }
                    });
        }
    }

    private void getDetailInfo() {
        if (TextUtils.isEmpty(getUserToken()) || TextUtils.isEmpty(mProjectId)) return;

        rx.Observable<JsonObject> observable;
        if (isManageType) {

            if(!"".equalsIgnoreCase(mCreditorRightsId))
            {
                mReviewId = "";
            }
//            if ("".equalsIgnoreCase(mReviewId)) {
            observable = Network
                    .getAPIService()
                    // TODO 参数待完善
                    .getExamineReviewDetail_g(getUserToken(), mProjectId, mReviewId,mCreditorRightsId);
        } else {
            observable = Network
                    .getAPIService()
                    // TODO 参数待完善
                    .getExamineReviewDetail_z1(getUserToken(), mProjectId, "", mCreditorRightsId);
        }

        observable
                .subscribeOn(rx.schedulers.Schedulers.io())
                .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext( JsonObject json ) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            showToast(json.get("msg").getAsString());
                            return;
                        } else {
                            LogUtil.v("--->Tag", json.toString());

                            JsonObject data = json.getAsJsonObject("data");



                            //债权申报信息
                            ZQBaseProjectCrDecInfo projectCrDec = new Gson().fromJson(data.get("projectCrDec"), ZQBaseProjectCrDecInfo.class);



                            mReviewId = projectCrDec.getReview().getId();
                            showImageDetail();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError( Throwable e ) {
                        super.onError(e);
                    }
                });
    }
}
